package com.blue.core.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

/**
 * 图片工具类
 * 
 * @author zhengj
 * @since 1.0 2016年7月27日
 */
public class PhotoUtil
{
	private static Logger logger = LoggerFactory.getLogger(PhotoUtil.class);

	private PhotoUtil()
	{
	}
	
	/**
	 * 按比例缩小图片不剪裁
	 * 
	 * @param src 源图片文件
	 * @param dest 目标图片文件
	 * @param width 目标图片文件宽度
	 * @param height 目标图片文件高度
	 */
	public static void thumb(File src, File dest, int width, int height)
	{
		try
		{
			Thumbnails.of(src)
								.size(width, height)
								.toFile(dest);
		}
		catch (IOException e)
		{
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 按比例缩小图片，居中剪裁
	 * 
	 * @param src 源图片文件
	 * @param dest 目标图片文件
	 * @param width 目标图片文件宽度
	 * @param height 目标图片文件高度
	 */
	public static void thumbCenter(File src, File dest, int width, int height)
	{
		try
		{
			BufferedImage image = ImageIO.read(src);
			
			Size thumbSize = getRegion(image.getWidth(), image.getHeight(), width, height);
			Thumbnails.of(image)
								.sourceRegion(Positions.CENTER, thumbSize.width, thumbSize.height)
								.size(width, height)
								.toFile(dest);
		}
		catch (IOException e)
		{
			throw new IllegalArgumentException(e);
		}
	}
	
	public static Size getRegion(int srcWidth, int srcHeight, int width, int height)
	{
		double dw = (double)srcWidth / width;
		double dh = (double)srcHeight / height;
		logger.debug("宽缩小比例：{}，高缩小比例：{}", dw, dh);
		
		int nw = srcWidth;
		int nh = srcHeight;
		
		if (dw <= dh)
		{
			nh = (int)(height * dw);
		}
		else
		{
			nw = (int)(width * dh);
		}
		logger.debug("宽：{}，高：{}", nw, nh);
		return new Size(nw, nh);
	}

	public static class Size
	{
		public int width;
		public int height;

		public Size(int width, int height)
		{
			this.width = width;
			this.height = height;
		}

		@Override
		public boolean equals(Object obj)
		{
			if (obj == null)
				return false;
			
			if (obj.getClass() != Size.class)
				return false;
			
			Size o = (Size)obj;
			return width == o.width && height == o.height;
		}
		
	}

}
